<template>
  <div v-if="isDragging" ref="floatingList" class="floating-list">5555666</div>
  <el-dialog
    v-model="dialogVisible"
    width="500"
    style="background-color: #282828"
  >
    <menuTree :buttonStatus="false" @customEvent="treeClick" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="update"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <RecycleScroller
    v-if="images.length > 0"
    class="scroller"
    :items="images"
    ref="scroller"
    :item-size="274"
    :itemSecondarySize="315"
    :buffer="200"
    gridItems="5"
    v-slot="{ item, index }"
    @update="change"
    @scroll-end="scrollEnd"
    :emitUpdate="true"
  >
    <div
      class="flex-center flex-wrap box"
      @click="select(item, index), selectNowItem(item, index)"
      @dblclick="goDetails(item, index)"
      @dragstart="handleDragStart"
      @dragend="handleDragEnd"
      @dragover.prevent
      @mousedown="startDrag($event, item)"
      @contextmenu.prevent="handleContextMenu"
      :class="selectIdList.includes(item.id) ? 'selected' : ''"
    >
      <!-- {{ item.labelList }}
      {{ item.valueList }} -->
      <div class="flex-center" style="width: 100%">
        <el-button size="small">{{ item.level }}</el-button>
      </div>
      <ImageWithMarks
        :imageUrl="item.url"
        :marks="item.marks"
        :lineWidth="lineWidth"
        :displaySize="item.displaySize"
        :borderColor="lineColor"
        :cropExpandSize="cropExpandSize"
        :lineStyle="lineStyle"
      ></ImageWithMarks>
      <div
        style="width: 245px; height: 10px; background-color: red"
        :style="{
          backgroundColor: item.borderColor,
        }"
      ></div>
    </div>
  </RecycleScroller>
</template>

<script setup>
import { RecycleScroller } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
import { storeToRefs } from "pinia";
import { useCounterStore } from "@/stores/counter";
import ImageWithMarks from "../../components/ImageWithMarksCopy.vue";
import { ElMessage } from "element-plus";

import { onMounted, ref, onUnmounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useControl } from "@/utils/useControl";
import { filePath as getFile } from "@/api/2d";
import { v4 as uuid } from "uuid";
import menuTree from "../../views/components/menuTree.vue";
// import { list } from "@/views/scroll/text";
const store = useCounterStore();
const {
  images,
  selectedIndex,
  item: selectItem,
  select,
  selectIdList,
} = useControl();
const {
  lineColor,
  cropExpandSize,
  lineWidth,
  lineStyle,
  dataList,
  list,
  idsList,
  changeKeyList,
  value,
  changeKeyIdList,
  lastNodeValue,
  workUserDomain,
  workPackId,
} = storeToRefs(store);
const router = useRouter();
const route = useRoute();
const scroller = ref(null);
// 保存滚动位置
function saveScrollPosition() {
  sessionStorage.setItem(
    `scrollPosition_${route.path}`,
    JSON.stringify({
      x: window.scrollX,
      y: window.scrollY,
    })
  );
}
router.beforeEach((to, from, next) => {
  saveScrollPosition();
  next();
});
onMounted(() => {
  window.addEventListener("keydown", handleKeyDown);
  const scrollPosition = sessionStorage.getItem(`scrollPosition_${route.path}`);
  if (scrollPosition) {
    const { x, y } = JSON.parse(scrollPosition);
    window.scrollTo(x, y);
  }
});
onUnmounted(() => {
  window.removeEventListener("keydown", handleKeyDown);
  saveScrollPosition();
});
const change = (startIndex, endIndex) => {
  let nowList = images.value.slice(startIndex, endIndex);
  let idList = [];
  nowList.forEach((i) => {
    idList.push(i.id);
    if (!idsList.value.includes(i.id)) {
      idsList.value.push(i.id);
    }
  });
  images.value.forEach((i) => {
    if (idList.includes(i.id) && !i.status) {
      i.url = "http://127.0.0.1:49999?filePath=" + i.filePath;
    }
  });
};
function handleKeyDown(event) {
  if (event.key == "a" || (event.key == "A" && event.key == "Ctrl")) {
    event.preventDefault();
    selectIdList.value = images.value.map((i) => i.id);
    selectItemList.value = images.value.map((i) => i);
  }
  if (event.key == "d" || (event.key == "D" && event.key == "Ctrl")) {
    event.preventDefault();
    selectIdList.value = [];
    selectItemList.value = [];
  }
}
// const selectIdList = ref([]);
const selectItemList = ref([]);
const selectNowItem = (item) => {
  if (selectIdList.value.includes(item.id)) {
    selectIdList.value = selectIdList.value.filter((i) => i != item.id);
    selectItemList.value = selectItemList.value.filter((i) => i.id != item.id);
  } else {
    selectIdList.value.push(item.id);
    selectItemList.value.push(item);
  }
};
const handleContextMenu = () => {
  if (!value.value) {
    ElMessage({
      message: "请选择value进行移动",
      type: "warning",
    });
    return;
  }
  if (selectIdList.value.length > 0) {
    dialogVisible.value = true;
  }
};
const selectNode = ref();
const lastSelectNode = ref();
const treeClick = (node, data) => {
  selectNode.value = node || "";
  lastSelectNode.value = data || "";
};
const dialogVisible = ref(false);

const update = () => {
  if (!selectNode.value) {
    ElMessage({
      message: "请选择value进行移动",
      type: "warning",
    });
    return;
  }

  selectItemList.value.forEach((val) => {
    //改变渲染的数据

    images.value.forEach((i) => {
      if (i.id == val.id) {
        i.labelList = i.labelList.map((item) =>
          item == lastNodeValue.value ? lastSelectNode.value : item
        );
        if (!changeKeyIdList.value.includes(i.id)) {
          changeKeyIdList.value.push(i.id);
        }
        i.valueList = i.valueList.map((item) =>
          item == value.value ? selectNode.value : item
        );
      }
    });

    //改变原数据
    dataList.value.forEach((i) => {
      i.details.forEach((item) => {
        if (item.markId == val.markId) {
          if (item.labelValue == value.value) {
            item.workPackId = workPackId.value;
            item.createUser = workUserDomain.value;
            item.history.push({
              value: item.labelValue,
              changeUser: item.createUser || "",
              workPackId: item.workPackId,
              changeTime: getFormattedDate(),
            });
            changeKeyList.value.push(item.labelKey);
            item.labelKey = lastSelectNode.value;
            item.labelValue = selectNode.value;
          }
        }
      });
    });
  });
  console.log("dataList", dataList.value);
  selectItemList.value = [];
  dialogVisible.value = false;
  selectIdList.value = [];
};
const clear = () => {
  selectItemList.value = [];
  selectIdList.value = [];
};

const goDetails = (items, index) => {
  router.push({
    path: "/main",
    query: {
      items: JSON.stringify(items),
      index,
    },
  });
  selectedIndex.value = index;
};
//获取时间
function getFormattedDate() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0"); // Months are zero-based
  const day = String(now.getDate()).padStart(2, "0");

  const hour = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hour}:${minutes}:${seconds}`;
}

const scrollEnd = () => {
  console.log("到底了");
};

const isDragging = ref(false);
const floatingList = ref(null);
const startDrag = (event, item) => {
  // isDragging.value = true;
  // document.addEventListener("mousemove", onDrag);
  // document.addEventListener("mouseup", endDrag);
};
const onDrag = (event) => {
  if (!isDragging.value || !floatingList.value) return;
  // 更新浮动列表的位置
  updateFloatingPosition(event.clientX, event.clientY);
};
const updateFloatingPosition = (x, y) => {
  const floatingListElement = floatingList.value;
  floatingListElement.style.left = `${x}px`;
  floatingListElement.style.top = `${y}px`;
};

const endDrag = () => {
  if (!isDragging.value) return;
  // 清理
  isDragging.value = false;
  document.removeEventListener("mousemove", onDrag);
  document.removeEventListener("mouseup", endDrag);
};

defineExpose({
  clear,
});
</script>

<style lang="scss" scoped>
.scroller {
  height: 90vh;
  margin-top: 5px;
  width: 83vw;
  background-color: #383838;
}

.box {
  border: 2px solid #181818;
  width: 100%;
  height: 100%;
}
.selected {
  background: #777777;
}

/* 节点文本颜色 */
::v-deep .el-tree-node__label {
  color: #fff;
}

/* 节点默认背景色 */
::v-deep .el-tree-node {
  background-color: #282828 !important;
}
.select {
  color: #2c2c2c;
}
.c-fff:hover {
  color: #2c2c2c !important; /* 替换为你想要的颜色 */
}
::v-deep .el-tree__empty-block {
  background-color: #282828;
}

.floating-list {
  position: absolute;
  background-color: white;
  border: 1px solid #ddd;
  padding: 5px;
  z-index: 1000;
}
</style>
